package com.rogue.blog.controller.image;

import com.rogue.blog.model.vo.image.CKFinderResponseVO;
import com.rogue.blog.service.image.ImageUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by 86101 on 2018-09-26.
 */
@Api(tags={"图片上传与加载"})
@RestController
@RequestMapping(value = "/image")
public class ImageUploadController {

    private final static Logger logger = LoggerFactory.getLogger(ImageUploadController.class);

    @Value("${upload.image.url}")
    private String imageUploadUrl;

    @Autowired
    private ImageUploadService imageUploadService;

    @ApiOperation(value = "上传图片")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public CKFinderResponseVO uploadImage(@RequestPart("upload") MultipartFile multipartFile) {
        CKFinderResponseVO ckFinderResponseVO = new CKFinderResponseVO();
        try {
            String imageRelativePath = imageUploadService.uploadImage(multipartFile);
            ckFinderResponseVO.setUploaded("1");
            ckFinderResponseVO.setUrl(imageUploadUrl + "?path=" + imageRelativePath);
        } catch (IOException e) {
            logger.error("ImageUploadController.uploadImage error", e);
            ckFinderResponseVO.setUploaded("0");
            ckFinderResponseVO.setUrl("");
        }
        return ckFinderResponseVO;
    }

    @ApiOperation(value = "加载图片")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public void loadImage(@RequestParam String path, HttpServletResponse response) {
        File image = imageUploadService.getImage(path);
        if (!image.exists()) {
            return;
        }
        try {
            response.reset();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("content-Disposition", "attachment;filename=" + image.getName());
            OutputStream os = response.getOutputStream();
            FileInputStream in = new FileInputStream(image);
            FileCopyUtils.copy(in, os);
            os.flush();
        } catch (Exception e) {
            logger.error("ImageUploadController.loadImage error", e);
        }
    }
}
